#!/bin/bash
# Michael P. Reilly (C) 2015 All rights reserved
# bash command completion script
# release $RelNo$ ($Revision$)

LOGFILE=/tmp/sshcmd_comp.log

_COMP_sshcmd () {
    local cur
    COMPREPLY=()
    cur=${COMP_WORDS[COMP_CWORD]}
    prev=${COMP_WORDS[COMP_CWORD-1]}
    if [ $COMP_CWORD -ge 3 ]; then
        prevprev=${COMP_WORDS[COMP_CWORD-2]}
    else
        prevprev=${COMP_WORDS[1]}
    fi
    options=$( ${COMP_WORDS[0]} --help | tr ' ' '\n' | sed -ne 's/,$//;s/=.*//;/^-/p' |
                sort)
    local wantfilelongopt="X--keyfile\nX--file\nX--input\n"
    local wantfileshortopt="X-f\nX-K\nX-I\n"
    case ${prev}${cur} in
        --file=|--keyfile=|--input=) prevprev=${prev}; prev=${cur}; cur="";;
    esac
    if [[ $cur == -* ]]; then
        COMPREPLY=( $(compgen -W "$options" -- "$cur") )
    elif [ "X$prev" = X--file -o "X$prev" = X-f ] ||
         [ "X$prev" = X--keyfile -o "X$prev" = X-K ] ||
         [ "X$prev" = X--input -o "X$prev" = X-I ] ||
         [ "X$prev" = X= -a \
           \( "X$prevprev" = X--keyfile -o \
              "X$prevprev" = X--file -o \
              "X$prevprev" = X--input \) ]; then
        if [[ $cur == "" ]]; then
            COMPREPLY=( $(compgen -f -o filenames) )
        elif [[ $cur == \~*/* ]]; then
            cur=${cur#\~/}
            COMPREPLY=( $(cd 2>/dev/null; compgen -P \~/ -o filenames -G "$cur"*) )
        else
            COMPREPLY=( $(compgen -o filenames -G "$cur"*) )
        fi
    elif [ "X$prev" = X--show -o "X$prev" = X-s ] ||
         [ "X$prev" = X= -o "X$prevprev" = X--show ]; then
         COMPREPLY=( $(compgen -W "all success failure" "$cur") )
    fi
    # uncomment for debugging
    #echo "C${COMP_WORDS[@]}" >> $LOGFILE
    #echo "${#COMP_WORDS[@]}|$COMP_CWORD|$cur|$prev|$prevprev" >> $LOGFILE
    #echo "X${COMPREPLY[*]}" >> $LOGFILE
    return 0
}

# uncomment for debugging
#echo "restarting sshcmd.comp" >> $LOGFILE

complete -F _COMP_sshcmd sshcmd

